import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart';

import 'detector_view.dart';
import 'painters/text_detector_painter.dart';

class TextRecognizerView extends StatefulWidget {
  @override
  State<TextRecognizerView> createState() => _TextRecognizerViewState();
}

class _TextRecognizerViewState extends State<TextRecognizerView> {
  var _script = TextRecognitionScript.latin;
  var _textRecognizer = TextRecognizer(script: TextRecognitionScript.latin);
  bool _canProcess = true;
  bool _isBusy = false;
  CustomPaint? _customPaint;
  String? _text;
  var _cameraLensDirection = CameraLensDirection.back;
  
  // OHOS 平台特定优化：记录最后处理时间
  DateTime? _lastProcessTime;
  // OHOS 平台处理计数器，用于定期跳帧
  int _frameCount = 0;

  @override
  void dispose() async {
    _canProcess = false;
    _textRecognizer.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(children: [
        DetectorView(
          title: 'Text Detector',
          customPaint: _customPaint,
          text: _text,
          onImage: _processImage,
          initialCameraLensDirection: _cameraLensDirection,
          onCameraLensDirectionChanged: (value) => _cameraLensDirection = value,
        ),
        Positioned(
            top: 30,
            left: 100,
            right: 100,
            child: Row(
              children: [
                Spacer(),
                Container(
                    decoration: BoxDecoration(
                      color: Colors.black54,
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(4.0),
                      child: _buildDropdown(),
                    )),
                Spacer(),
              ],
            )),
      ]),
    );
  }

  Widget _buildDropdown() => DropdownButton<TextRecognitionScript>(
        value: _script,
        icon: const Icon(Icons.arrow_downward),
        elevation: 16,
        style: const TextStyle(color: Colors.blue),
        underline: Container(
          height: 2,
          color: Colors.blue,
        ),
        onChanged: (TextRecognitionScript? script) {
          if (script != null) {
            setState(() {
              _script = script;
              _textRecognizer.close();
              _textRecognizer = TextRecognizer(script: _script);
            });
          }
        },
        items: TextRecognitionScript.values
            .map<DropdownMenuItem<TextRecognitionScript>>((script) {
          return DropdownMenuItem<TextRecognitionScript>(
            value: script,
            child: Text(script.name),
          );
        }).toList(),
      );

  Future<void> _processImage(InputImage inputImage) async {
    // 快速失败检查
    if (!_canProcess || _isBusy) return;

    // OHOS 平台特定优化：增加跳帧处理，降低处理频率
    if (Platform.isOhos) {
      _frameCount++;
      // 每3帧处理一次，进一步降低处理频率
      if (_frameCount % 3 != 0 && inputImage.type != InputImageType.file) {
        return;
      }
      
      // 增加最小处理间隔检查
      final now = DateTime.now();
      if (_lastProcessTime != null && inputImage.type != InputImageType.file) {
        final timeSinceLastProcess = now.difference(_lastProcessTime!);
        // OHOS 平台最小处理间隔设为 800ms
        if (timeSinceLastProcess.inMilliseconds < 800) {
          return;
        }
      }
      _lastProcessTime = now;
    }

    _isBusy = true;

    try {
      // 延迟状态更新，避免不必要的重建
      if (_text != null && _text!.isNotEmpty) {
        setState(() {
          _text = '';
        });
      }

      // 处理图像
      final recognizedText = await _textRecognizer.processImage(inputImage);

      // 判断是否有识别结果
      final hasText = recognizedText.text.isNotEmpty;

      if (hasText) {
        await _handleTextResults(recognizedText, inputImage);
      } else {
        await _handleNoTextResults();
      }

      // 添加处理间隔，OHOS 平台使用更长的延迟
      if (Platform.isOhos && inputImage.type != InputImageType.file) {
        // OHOS 平台延迟时间增加
        if (hasText) {
          await Future<void>.delayed(const Duration(milliseconds: 2000));
        } else {
          await Future<void>.delayed(const Duration(milliseconds: 500));
        }
      }

    } catch (e, stackTrace) {
      debugPrint('Text recognition error: $e');
      debugPrint('Stack trace: $stackTrace');
      // 发生错误时也要重置状态
      _isBusy = false;
      if (mounted) {
        setState(() {
          _text = 'Error processing image: $e';
        });
      }
      return;
    } finally {
      // 使用 finally 确保 _isBusy 一定会被重置
      _isBusy = false;
    }
  }

  /// 处理有识别结果的情况
  Future<void> _handleTextResults(RecognizedText recognizedText, InputImage inputImage) async {
    if (inputImage.metadata?.size != null && inputImage.metadata?.rotation != null) {
      // 使用自定义绘制显示边界框
      final painter = TextRecognizerPainter(
        recognizedText,
        inputImage.metadata!.size,
        inputImage.metadata!.rotation,
        _cameraLensDirection,
      );
      _customPaint = CustomPaint(painter: painter);
      _text = ''; // 清空文本显示
    } else {
      // 构建识别结果文本
      _text = 'Recognized text:\n\n${recognizedText.text}';
      _customPaint = null;
    }

    // 只在 mounted 时更新 UI
    if (mounted) {
      setState(() {});
    }

    // 在结果处理后再添加一个短暂延迟
    await Future<void>.delayed(const Duration(milliseconds: 100));
  }

  /// 处理无识别结果的情况
  Future<void> _handleNoTextResults() async {
    _text = 'Recognized text:';
    _customPaint = null;

    if (mounted) {
      setState(() {});
    }
  }
}
